var $jq = jQuery.noConflict();
var xhr = false;

$jq(document).ready(function(){
    $jq("#posts").find("dt").click(function()
    {
        var clickedPostId = $jq(this).attr("id");
        getPostsXML(clickedPostId);
    });
});

function getPostsXML(getPostId)
{
    if (window.XMLHttpRequest)
    {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        try
        {
           xhr =  new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
            // TODO: add error handling.
        }
    }

    if (xhr)
    {
        xhr.onreadystatechange = onPostsXMLReceived;
        var url = "Feedback?mode=getPostDetails&postID=" + getPostId;
        xhr.open("GET", url , true);
        xhr.send(null);
    }
    else
    {
        // TODO: add error handling.
    }
}

function onPostsXMLReceived()
{
    if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseXML) 
    // && xhr.responseXML.contentType == "text/xml") // contentType is not supported by IE 8.
    {
        /*
         * dl = dict. list
         * dt = dict. term
         * dd = dict. definition
         */

        // Create a temporary div element to be parent of the incoming xml.
        //var tempDiv = document.createElement("div");
        //var details = xhr.responseXML.getElementsByTagName("details");
        //$jq(details).appendTo(tempDiv);
        var detailsArray    = xhr.responseXML.getElementsByTagName("details"); // $jq(tempDiv).find("details");
        var detailsId       = $jq(detailsArray[0]).attr("id");
        var detailsString   = $jq(detailsArray[0]).text();
        var targetDtString = "#" + detailsId;
        var targetDtArray   = $jq(targetDtString);

        $jq("<dd>" + detailsString + "</dd>").insertAfter(targetDtArray[0]);

        $jq("#posts").find(targetDtString).unbind('click');
        $jq("#posts").find(targetDtString).click(function()
        {
            $jq(this).next().slideToggle();
        });
    }
    else if (xhr.readyState == 4 && xhr.status != 200)
    {
        // TODO: add error handling.
    }
}